package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.elinkway.infinitemovies.adapter.HotSearchKeyGridAdapter;
import com.elinkway.infinitemovies.adapter.SearchKeywordListAdapter;
import com.elinkway.infinitemovies.adapter.SearchResultAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.bean.SearchKeyWords;
import com.elinkway.infinitemovies.bean.SearchResult;
import com.elinkway.infinitemovies.bean.SearchResultList;
import com.elinkway.infinitemovies.bean.SearchResultType;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataSearchBean;
import com.elinkway.infinitemovies.bigdata.RealDataApi;
import com.elinkway.infinitemovies.dao.SearchHistoryDao;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.SearchKeyWordsParser;
import com.elinkway.infinitemovies.http.parser.SearchResultParser;
import com.elinkway.infinitemovies.http.parser.SearchSuggestParser;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.SearchDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.SearchResultTabStrip;
import com.google.gson.Gson;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActivity extends Activity {

    public static final String TAG = "SearchActivity";

    private HomeBackReceiver mHomeKeyReceiver = null;

    private AutoCompleteTextView mSearchText;
    private TextView mCancel;
    private ImageView mDelete;
    private LinearLayout mSearchHeader;
    private TextView mSearchHeaderText;
    private ImageView mClearHistoryIv;
    private SearchResultTabStrip tabs;
    private ScrollView searchKeysScroll;
    private LinearLayout hotSearchLl;
    private GridView hotKeyGridView;
    private ListView lvKeywords;
    private ListView lvResult;
    private String oldWord;
    private RequestHotWordsTask requestHotTask;
    private RequestSuggestWordsTask requestSuggestTask;
    private static RequestSearchResultTask requestResultTask;
    private View mLoadingView;
    private ImageView mLoadingIv;
    private SearchKeyWords hotwords;
    private SearchKeyWords suggestwords;
    private SearchKeyWords historywords;
    private SearchResultList resultList;
    private SearchKeywordListAdapter mKeywordAdapter;
    private HotSearchKeyGridAdapter mHotKeyAdapter;
    private SearchResultAdapter mResultAdapter;
    private View searchResultFooter;
    private LinearLayout mListContainer;
    private LinearLayout emptyResultView;
    private RelativeLayout resultContainer;
    private ProgressBar resultLoading;
    private LinearLayout resultLoadFailed;
    private int currentPage = 1;
    private SearchHistoryDao searchHistoryDao;
    private View searchHistoryFooter;
    private SearchState state;
    private SearchTextWatcher mTextWatcher;
    private String searchVt = "";
    private boolean isShowAllHistory;
    private String realRequestWord;
    private String mDefaultSearchKey = "";
    private SearchDataRecord mSearchDataRecord;
    public AnimationDrawable animationDrawable = null;

    //网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;

    // private LinearLayout mResultHeader;
    // private TextView mResultHeaderText;
    private enum SearchState {
        HISTORY(1), SUGGEST(2), RESULT(3), LOADING(4);

        private int state;

        private SearchState(int state) {
            this.state = state;
        }

        public int getState() {
            return state;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_main);
        // Show the Up button in the action bar.
        if (getIntent() != null) {
            mDefaultSearchKey = getIntent().getStringExtra("searchKey");
        }
        searchHistoryDao = new SearchHistoryDao(this);
        historywords = searchHistoryDao.getAll();
        String hotword = SharePreferenceManager.getVaule(getApplicationContext(), SharePreferenceManager.SEARCH_HOT_DATA, "");
        if (!TextUtils.isEmpty(hotword)) {
            try {
                Gson gson = new Gson();
                hotwords = gson.fromJson(hotword, SearchKeyWords.class);
            } catch (Exception e) {
                hotwords = null;
            }
        }
        initView();
        initEditView();
        registerHomeKeyReceiver(this);
        mSearchDataRecord = MyDataRecordCreater.build(SearchDataRecord.class); // 埋点
        mSearchDataRecord.setCur_url(SearchDataRecord.CUR_URL_SEARCH);
        setStatisticsLog("41",null,null,null,null,null,null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterHomeKeyReceiver(this);
    }

    private void initView() {
        mLoadingView = findViewById(R.id.load_layout);
        mLoadingView.setVisibility(View.GONE);
        mLoadingIv = (ImageView) findViewById(R.id.loading_progressBar);
        mListContainer = (LinearLayout) findViewById(R.id.search_list_container);
        mSearchText = (AutoCompleteTextView) findViewById(R.id.et_search_topbar_edit);
        mCancel = (TextView) findViewById(R.id.tv_search_submit);
        mDelete = (ImageView) findViewById(R.id.search_edit_delete_button);
        searchKeysScroll = (ScrollView) findViewById(R.id.search_keywords_scroll);
        hotSearchLl = (LinearLayout) findViewById(R.id.hot_search_ll);
        lvKeywords = (ListView) findViewById(R.id.search_keywords_list);
        hotKeyGridView = (GridView) findViewById(R.id.hot_searchkey_gv);
        lvResult = (ListView) findViewById(R.id.search_result_list);
        tabs = (SearchResultTabStrip) findViewById(R.id.search_result_tab);
        emptyResultView = (LinearLayout) findViewById(R.id.search_no_result);
        resultContainer = (RelativeLayout) findViewById(R.id.search_result_container);
        resultLoading = (ProgressBar) findViewById(R.id.search_result_loading);
        resultLoadFailed = (LinearLayout) findViewById(R.id.search_result_load_failed);
        mSearchHeader = (LinearLayout) UIs.inflate(this,
                R.layout.search_header, null);
        mSearchHeaderText = (TextView) mSearchHeader
                .findViewById(R.id.search_main_title);
        mClearHistoryIv = (ImageView) mSearchHeader.findViewById(R.id.clear_history_iv);
        mClearHistoryIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                searchHistoryDao.delAll();
                historywords = new SearchKeyWords();
                mKeywordAdapter.clear();
                if (lvKeywords.getFooterViewsCount() != 0) {
                    lvKeywords.removeFooterView(searchHistoryFooter);
                }
                lvKeywords.removeHeaderView(mSearchHeader);
                BigDataSearchBean clearBean = new BigDataSearchBean();
                clearBean.setModule("search_history");
                clearBean.setActionCode("2");
                clearBean.setClickArea("clear_button");
                BigDataApi.bigDataSearchReport(clearBean);
            }
        });
        lvKeywords.addHeaderView(mSearchHeader);

        searchResultFooter = UIs.inflate(this, R.layout.search_result_footer,
                null);
        hotKeyGridView.setOnItemClickListener(new OnHotKeyClickListener());
        if (hotwords != null) {
            displayHot(hotwords);
        }
        lvResult.setOnScrollListener(new OnResultListScrollListener());
        lvKeywords.setOnItemClickListener(new OnKeywordClickListener());
        lvResult.setOnItemClickListener(new OnResultItemClickListener());
        tabs.setOnTabClickListener(new SearchResultTabStrip.OnTabClickListener() {

            @Override
            public void onTabClick(int position, View v) {
                SearchResultType resultType = (SearchResultType) v.getTag();
                if (requestResultTask != null
                        && !requestResultTask.isCancelled()) {
                    requestResultTask.cancel();
                    requestResultTask = null;
                }
                currentPage = 1;
                searchVt = resultType.getVt();

                BigDataSearchBean tabBean = new BigDataSearchBean();
                tabBean.setModule("search_rst_page");
                tabBean.setClickArea("tab_text");
                tabBean.setQuery(oldWord);
                tabBean.setParentEid(resultList == null ? "" : resultList.getEid());
                requestResultTask = new RequestSearchResultTask(
                        MoviesApplication.getInstance(), currentPage, oldWord, searchVt, tabBean);
                requestResultTask.start();

                setStatisticsLog("0",SearchDataRecord.AP_SEARCH_TAB,oldWord,null,searchVt,null,null);
            }
        });
        searchHistoryFooter = UIs.inflate(this, R.layout.search_history_footer,
                null);
        searchHistoryFooter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowAllHistory = true;
                setState(SearchState.HISTORY, historywords);
            }
        });
        requestHotTask = new RequestHotWordsTask(MoviesApplication.getInstance());
        requestHotTask.start();
    }

    private void initEditView() {
        String str = mSearchText.getText().toString().trim();
        if (str == null || str.equals("")) {
            setState(SearchState.HISTORY, historywords);
            oldWord = null;
        }

        mCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                UIs.hideSoftkeyboard(SearchActivity.this);
                BigDataSearchBean cancelBean = new BigDataSearchBean();
                cancelBean.setModule("home_page");
                cancelBean.setActionCode("2");
                cancelBean.setClickArea("cancel_button");
                BigDataApi.bigDataSearchReport(cancelBean);
                finish();
            }
        });
        mTextWatcher = new SearchTextWatcher();
        mSearchText.addTextChangedListener(mTextWatcher);
        mDelete.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mTextWatcher.pauseOneTime();
                    mSearchText.setText("");
                }
                return true;
            }
        });
        mSearchText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView arg0, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && actionId == EditorInfo.IME_ACTION_UNSPECIFIED && event.getAction() == KeyEvent.ACTION_DOWN) || actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null
                        && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event
                        .getAction() == KeyEvent.ACTION_DOWN)) {
                    String requestWord = mSearchText.getText().toString().trim();
                    if ((!("".equals(requestWord)))) {
                        if (requestResultTask != null
                                && !requestResultTask.isCancelled()) {
                            requestResultTask.cancel();
                        }

                        BigDataSearchBean searchBean = new BigDataSearchBean();
                        searchBean.setModule("suggest_list");
                        searchBean.setClickArea("search_button");
                        searchBean.setQuery(requestWord);
                        if (suggestwords != null) {
                            searchBean.setEid(suggestwords.getEid());
                            searchBean.setExperimentId(suggestwords.getExperimentId());
                            searchBean.setIsTrigger(suggestwords.getIsTrigger());
                        }
                        BigDataApi.bigDataSearchReport(searchBean);

                        String suggestword = "";

                        if (suggestwords != null) {
                            suggestword = suggestwords.getEid();
                            searchBean.setParentEid(suggestword);
                        }

                        requestResultTask = new RequestSearchResultTask(
                                MoviesApplication.getInstance(), 1, requestWord, searchVt, searchBean);
                        setState(SearchState.LOADING, new SearchKeyWords());
                        requestResultTask.start();

                        RealDataApi.RealDataSearchReport(suggestword, requestWord);

                        setStatisticsLog("0",SearchDataRecord.AP_SEARCH_BTN,requestWord,null,null,null,null);

                    }
                    return true;
                }
                return false;

            }
        });
        if (!TextUtils.isEmpty(mDefaultSearchKey)) {
            mSearchText.setHint(mDefaultSearchKey);
            mSearchText.setFocusable(true);
            mSearchText.setFocusableInTouchMode(true);
            mSearchText.requestFocus();
        }
    }

    public static void launch(Activity activity) {
        Intent intent = new Intent(activity, SearchActivity.class);
        UmengEventPoster.postChannelClick(UmengEventPoster.CHANNEL_SEARCH);
        activity.startActivity(intent);
    }

    //热词按键监听
    private class OnHotKeyClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            searchVt = ""; // 搜索类型清空
            currentPage = 1;
            String searchWord = hotwords.getWords().get(position);
            mTextWatcher.pauseOneTime();
            mSearchText.setText(searchWord);
            mSearchText.setSelection(searchWord.length());
            if (requestResultTask != null
                    && !requestResultTask.isCancelled()) {
                requestResultTask.cancel();
            }

            BigDataSearchBean hotItemBean = new BigDataSearchBean();
            hotItemBean.setModule("hot_search");
            hotItemBean.setClickArea("text");
            hotItemBean.setQuery(searchWord);
            hotItemBean.setPosition(position + "");

            Map<String, String> dataMap = BigDataApi.createDataMap("0", "热门搜索=" + searchWord, "0", "-", "", "-");
            dataMap.put("cur_url", BigDataConstants.PGV_CURRENT_ID_SEARCH);
            BigDataApi.bigDataCommonReport(dataMap, SearchActivity.this);

            requestResultTask = new RequestSearchResultTask(
                    MoviesApplication.getInstance(), currentPage, searchWord, searchVt, hotItemBean);
            setState(SearchState.LOADING, new SearchKeyWords());
            requestResultTask.start();

            setStatisticsLog ("0",SearchDataRecord.AP_SEARCH_HOT,searchWord,null,null,null,null);

        }
    }

    //提示，历史公用按键监听
    private class OnKeywordClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            searchVt = ""; // 搜索类型清空
            currentPage = 1;
            int clickPosition = position - 1;
            String searchWord = "";
            BigDataSearchBean keyBean = new BigDataSearchBean();
            switch (state) {
                case HISTORY:
                    if (clickPosition >= 0) {
                        searchWord = historywords.getWords().get(clickPosition);

                        keyBean.setModule("search_history");
                        keyBean.setClickArea("text");
                        keyBean.setQuery(searchWord);

                        setStatisticsLog("0",SearchDataRecord.AP_SEARCH_HISTORY,searchWord,null,null,null,null);
                    }
                    break;
                case SUGGEST:
                    searchWord = suggestwords.getWords().get(position);

                    keyBean.setModule("suggest_list");
                    keyBean.setClickArea("text");
                    keyBean.setSuggestText(searchWord);
                    keyBean.setQuery(oldWord);
                    keyBean.setEid(suggestwords.getEid());
                    keyBean.setExperimentId(suggestwords.getExperimentId());
                    keyBean.setIsTrigger(suggestwords.getIsTrigger());
                    keyBean.setPosition(position + "");
                    BigDataApi.bigDataSearchReport(keyBean);
                    keyBean.setParentEid(suggestwords.getEid());
                    RealDataApi.RealDataSearchReport(suggestwords.getEid(), searchWord);

                    setStatisticsLog("0",SearchDataRecord.AP_SEARCH_ASSOCIATION,searchWord,null,null,null,null);
                    break;
                default:
                    searchWord = "";
                    break;
            }
            if (!TextUtils.isEmpty(searchWord)) {
                mTextWatcher.pauseOneTime();
                mSearchText.setText(searchWord);
                try {
                    mSearchText.setSelection(searchWord.length());
                } catch (Exception e) {
                    com.apkfuns.logutils.LogUtils.e(e.getMessage());
                }
                if (requestResultTask != null
                        && !requestResultTask.isCancelled()) {
                    requestResultTask.cancel();
                }
                requestResultTask = new RequestSearchResultTask(
                        MoviesApplication.getInstance(), currentPage, searchWord, searchVt, keyBean);
                setState(SearchState.LOADING, new SearchKeyWords());
                requestResultTask.start();
            }
        }
    }

    private class OnResultItemClickListener implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                long arg3) {
            SearchResult searchResult;
            if (position < resultList.getResultList().size()) {

                searchResult = resultList.getResultList().get(position);

                BigDataSearchBean resultBean = new BigDataSearchBean();
                resultBean.setModule("search_rst_page");
                resultBean.setClickArea("text");
                resultBean.setQuery(realRequestWord);
                resultBean.setActionCode("1");
                resultBean.setPosition(position + "");
                resultBean.setEid(resultList.getEid());
                resultBean.setExperimentId(resultList.getExperimentStr());
                resultBean.setIsTrigger(resultList.getTriggerStr());
                resultBean.setGid(resultList.getResultList().get(position).getGlobalId());
                BigDataApi.bigDataSearchReport(resultBean);
                VideoDetailActivity.launch(SearchActivity.this, searchResult.getAid(), searchResult.getVt(), searchResult.getName(),
                        searchResult.getSrc(), "", "search", "0",resultList.getEid(),"");
                RealDataApi.RealDataClickReport(resultList.getEid(), "", searchResult.getAid(), searchResult.getCategory(),"");

                setStatisticsLog("0",SearchDataRecord.AP_SEARCH_RESULT,null,searchResult.getAid(),searchResult.getVt(),searchResult.getName(),null);
            }
        }

    }

    // 埋点
    private void setStatisticsLog(String aCode,String ap,String queryName,String aid,String vt,String videoName,String tab) {
        if (mSearchDataRecord == null) {
            return;
        }
        if (!TextUtils.isEmpty(aCode)) {
            mSearchDataRecord.setAcode(aCode);
        } else {
            mSearchDataRecord.setAcode("");
        }
        if (!TextUtils.isEmpty(ap)) {
            mSearchDataRecord.setAp(ap);
        } else {
            mSearchDataRecord.setAp("");
        }
        if (!TextUtils.isEmpty(queryName)) {
            mSearchDataRecord.setQueryName(queryName);
        } else {
            mSearchDataRecord.setQueryName("");
        }
        if (!TextUtils.isEmpty(aid)) {
            mSearchDataRecord.setAid(aid);
        } else {
            mSearchDataRecord.setAid("");
        }
        if (!TextUtils.isEmpty(vt)) {
            mSearchDataRecord.setVt(vt);
        } else {
            mSearchDataRecord.setVt("");
        }
        if (!TextUtils.isEmpty(videoName)) {
            mSearchDataRecord.setVideoName(videoName);
        } else {
            mSearchDataRecord.setVideoName("");
        }
        if (!TextUtils.isEmpty(tab)) {
            mSearchDataRecord.setTab(tab);
        } else {
            mSearchDataRecord.setTab("");
        }
        RealmDaoManager.addMyDataRecord(mSearchDataRecord);
    }

    /**
     * @param words
     */

    // 切换热词显示页
    private void displayHot(SearchKeyWords words) {
        if (searchKeysScroll.getVisibility() == View.GONE) {
            searchKeysScroll.setVisibility(View.VISIBLE);
        }
        hotSearchLl.setVisibility(View.VISIBLE);
        if (null != mHotKeyAdapter) {
            mHotKeyAdapter.resetData(words);
        } else {
            mHotKeyAdapter = new HotSearchKeyGridAdapter(SearchActivity.this, words);
            hotKeyGridView.setAdapter(mHotKeyAdapter);
        }
    }

    private void displayLoading() {
        hotSearchLl.setVisibility(View.GONE);
        lvResult.setVisibility(View.GONE);
        searchKeysScroll.setVisibility(View.GONE);
        resultLoadFailed.setVisibility(View.GONE);
        emptyResultView.setVisibility(View.GONE);
        UIs.hideSoftkeyboard(this);
        mLoadingView.setVisibility(View.VISIBLE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.start();
        state = SearchState.LOADING;

    }
    // 切换 提示显示页
    private void displaySuggest(SearchKeyWords words) {
        if (null != mKeywordAdapter) {
            mKeywordAdapter.resetData(words, "suggest");
        } else {
            mKeywordAdapter = new SearchKeywordListAdapter(SearchActivity.this,
                    words, "suggest");
            lvKeywords.setAdapter(mKeywordAdapter);
        }
        hotSearchLl.setVisibility(View.GONE);
        if (lvKeywords.getFooterViewsCount() != 0) {
            lvKeywords.removeFooterView(searchHistoryFooter);
        }
        if (lvKeywords.getHeaderViewsCount() != 0) {
            lvKeywords.removeHeaderView(mSearchHeader);
        }
        if (searchKeysScroll.getVisibility() == View.GONE) {
            resultContainer.setVisibility(View.GONE);
            lvResult.setVisibility(View.GONE);
            searchKeysScroll.setVisibility(View.VISIBLE);
        }
        state = SearchState.SUGGEST;
    }

    private void displayHistory(SearchKeyWords words) {
        boolean isAddFooterView = false;
        if (words.getWords().size() != 0) {
            SearchKeyWords partWords = new SearchKeyWords();
            if (isShowAllHistory) {
                if (lvKeywords.getFooterViewsCount() != 0) {
                    lvKeywords.removeFooterView(searchHistoryFooter);
                    isAddFooterView = false;
                }
                partWords = words;
            } else {
                if (words.getWords().size() > 5) {
                    if (lvKeywords.getFooterViewsCount() == 0) {
                        lvKeywords.addFooterView(searchHistoryFooter);
                        isAddFooterView = true;
                    }
                    List<String> newWords = new ArrayList<String>();
                    for (int i = 0; i < 5; i++) {
                        newWords.add(words.getWords().get(i));
                    }
                    partWords.setWords(newWords);
                } else {
                    if (lvKeywords.getFooterViewsCount() != 0) {
                        lvKeywords.removeFooterView(searchHistoryFooter);
                        isAddFooterView = false;
                    }
                    partWords = words;
                }
            }

            if (null != mKeywordAdapter) {
                mKeywordAdapter.isAddFooterView(isAddFooterView);
                mKeywordAdapter.resetData(partWords, "history");
            } else {
                mKeywordAdapter = new SearchKeywordListAdapter(SearchActivity.this, partWords, "history");
                mKeywordAdapter.isAddFooterView(isAddFooterView);
                lvKeywords.setAdapter(mKeywordAdapter);
            }

            hotSearchLl.setVisibility(View.VISIBLE);
            if (lvKeywords.getHeaderViewsCount() == 0) {
                lvKeywords.addHeaderView(mSearchHeader);
            }
            mSearchHeaderText.setText(R.string.search_history);
            resultContainer.setVisibility(View.GONE);
            lvResult.setVisibility(View.GONE);
            if (searchKeysScroll.getVisibility() == View.GONE) {
                searchKeysScroll.setVisibility(View.VISIBLE);
            }
            state = SearchState.HISTORY;
        }
    }

    // 切换结果显示页
    private void displayResult(SearchResultList resultList) {
        isFirstHasDataSuccess = true;
        mLoadingView.setVisibility(View.GONE);
        animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
        animationDrawable.stop();
        // 防止重复addFooterView
        if (lvResult.getFooterViewsCount() == 0) {
            lvResult.addFooterView(searchResultFooter);
        }
        if (null != mResultAdapter) {
            mResultAdapter.resetData(resultList);
        } else {
            mResultAdapter = new SearchResultAdapter(this, resultList);
            lvResult.setAdapter(mResultAdapter);
        }
        if (resultContainer.getVisibility() == View.GONE) {
            tabs.setList(lvResult);
            tabs.scrollTo(0, 0);
        }
        if (resultContainer.getVisibility() == View.GONE) {
            searchKeysScroll.setVisibility(View.GONE);
            resultContainer.setVisibility(View.VISIBLE);

            // 三星 Note 切换结果页关键词列表有几率残留在屏幕
            mListContainer.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mListContainer.invalidate();
                }
            }, 100L);
        }
        if (resultList.getResultList().size() == 0) {
            emptyResultView.setVisibility(View.VISIBLE);
            lvResult.setVisibility(View.GONE);
        } else {
            emptyResultView.setVisibility(View.GONE);
            lvResult.setVisibility(View.VISIBLE);
        }
        lvResult.postDelayed(new Runnable() {

            @Override
            public void run() {
                lvResult.setSelectionFromTop(0, UIs.dipToPx(35));

            }
        }, 10L);
        setLoadingVisibile(false);
        UIs.hideSoftkeyboard(this);
        resultLoading.requestLayout();
        state = SearchState.RESULT;
    }


    private void setLoadingVisibile(boolean flag) {
        if (flag) {
            LogUtils.i("search", "loading visible");
            if (resultLoading.getVisibility() != View.VISIBLE) {
                resultLoading.setVisibility(View.VISIBLE);
                LogUtils.i("search", "loading visible complete");
            }
        } else {
            LogUtils.e("search", "loading gone");
            if (resultLoading.getVisibility() != View.GONE) {
                resultLoading.setVisibility(View.GONE);
                LogUtils.e("search", "loading gone complete");
            }
        }
    }

    // 调用display方法 加载热词
    private class RequestHotWordsTask extends
            MoviesHttpAsyncTask<SearchKeyWords> {

        @Override
        public void netNull() {
            super.netNull();
            UIs.showToast(R.string.search_net_error);
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            UIs.showToast(R.string.search_net_error);
        }

        @Override
        public boolean onPreExecute() {
            if (requestResultTask != null && !requestResultTask.isCancelled()) {
                requestResultTask.cancel();
            }
            if (requestSuggestTask != null && !requestSuggestTask.isCancelled()) {
                requestSuggestTask.cancel();
            }
            return super.onPreExecute();
        }

        public RequestHotWordsTask(Context context) {
            super(context);
        }

        @Override
        public LVideoDataHull<SearchKeyWords> doInBackground() {
            return MoviesHttpApi
                    .requestSearchHotData(new SearchKeyWordsParser());
        }

        @Override
        public void onPostExecute(int updateId, SearchKeyWords result) {
            hotwords = result;
            if (hotwords != null) {
                Gson gson = new Gson();
                SharePreferenceManager.saveVaule(getApplicationContext(), SharePreferenceManager.SEARCH_HOT_DATA, gson.toJson(hotwords));
            }
            displayHot(result);
        }

    }

    // 调用display方法 加载提示
    private class RequestSuggestWordsTask extends
            MoviesHttpAsyncTask<SearchKeyWords> {

        @Override
        public void netNull() {
            super.netNull();
            UIs.showToast(R.string.search_net_error);
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            UIs.showToast(R.string.search_net_error);
        }

        @Override
        public boolean onPreExecute() {
            if (requestHotTask != null && !requestHotTask.isCancelled()) {
                requestHotTask.cancel();
            }
            if (requestResultTask != null && !requestResultTask.isCancelled()) {
                requestResultTask.cancel();
            }
            return super.onPreExecute();
        }

        private String requestWord;

        public RequestSuggestWordsTask(Context context, String wd) {
            super(context);
            this.requestWord = wd;
        }

        @Override
        public LVideoDataHull<SearchKeyWords> doInBackground() {
            return MoviesHttpApi.requestSearchSuggest(
                    new SearchSuggestParser(), requestWord);
        }

        @Override
        public void onPostExecute(int updateId, SearchKeyWords result) {
            if (result.getWords().size() != 0) {
                suggestwords = result;
                suggestwords.setSearchKey(requestWord);
                setState(SearchState.SUGGEST, suggestwords);
            }
        }

    }

    private boolean isFirstHasDataSuccess = false;

    // 结果列表的请求，主动判断是否为加载更多，并根据获取结果隐藏加载进度条
    private class RequestSearchResultTask extends
            MoviesHttpAsyncTask<SearchResultList> {
        private int requestPage;
        private String requestWord;
        private String requestVt;
        private BigDataSearchBean bean;

        public RequestSearchResultTask(Context context, int requestPage,
                                       String requestWord, String searchVt, BigDataSearchBean bean) {
            super(context);
            this.requestPage = requestPage;
            this.requestWord = requestWord;
            this.requestVt = searchVt;
            this.bean = bean;
            realRequestWord = requestWord;
        }

        @Override
        public void netNull() {
            super.netNull();
            setLoadingVisibile(false);
            resultContainer.setVisibility(View.VISIBLE);
            resultLoadFailed.setVisibility(View.VISIBLE);
            mLoadingView.setVisibility(View.GONE);
            animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
            if (animationDrawable.isRunning()) {
                animationDrawable.stop();
            }

        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            setLoadingVisibile(false);
            resultContainer.setVisibility(View.VISIBLE);
            resultLoadFailed.setVisibility(View.VISIBLE);
            mLoadingView.setVisibility(View.GONE);
            animationDrawable = (AnimationDrawable) mLoadingIv.getDrawable();
            if (animationDrawable.isRunning()) {
                animationDrawable.stop();
            }
        }

        @Override
        public boolean onPreExecute() {
            if (requestHotTask != null && !requestHotTask.isCancelled()) {
                requestHotTask.cancel();
            }
            if (requestSuggestTask != null && !requestSuggestTask.isCancelled()) {
                requestSuggestTask.cancel();
            }
            if (requestPage == 1) {
                lvResult.setVisibility(View.GONE);
                emptyResultView.setVisibility(View.GONE);
                resultLoadFailed.setVisibility(View.GONE);
                setLoadingVisibile(true);
            }
            return super.onPreExecute();
        }

        @Override
        public LVideoDataHull<SearchResultList> doInBackground() {
            return MoviesHttpApi.requestSearchResult(new SearchResultParser(),
                    requestPage, requestWord,
                    MoviesConstant.SEARCH_RESULT_REQUEST_SIZE, requestVt);
        }

        @Override
        public void onPostExecute(int updateId, SearchResultList result) {
            saveToHistory(this.requestWord);
            if (result != null && bean != null) {
                bean.setActionCode("0");
                bean.setEid(result.getEid());
                bean.setExperimentId(result.getExperimentStr());
                bean.setIsTrigger(result.getTriggerStr());
                bean.setStatus("success");
                BigDataApi.bigDataSearchReport(bean);
                if (result.getResultList() == null || result.getResultList().size() == 0) {
                    setStatisticsLog("41",SearchDataRecord.AP_SEARCH_RESULT_NULL,this.requestWord,null,this.requestVt,null,null);
                } else {
                    setStatisticsLog("41",SearchDataRecord.AP_SEARCH_RESULT,this.requestWord,null,this.requestVt,null,null);
                }
            }

            if (requestPage == 1) {
                resultList = result;
                if (!isFirstHasDataSuccess) {
                    resultContainer.setVisibility(View.GONE);
                }
                setState(SearchState.RESULT, resultList);
            } else {
                mResultAdapter.loadMoreData(result);
            }
            currentPage++;
            oldWord = requestWord;
            if (lvResult.getFooterViewsCount() > 0 && result.getResultList().size() < MoviesConstant.SEARCH_RESULT_REQUEST_SIZE) {
                lvResult.removeFooterView(searchResultFooter);
            }
        }
    }

    // 结果列表的自动加载
    private class OnResultListScrollListener implements OnScrollListener {
        private int lastVisibleIndex;

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                             int visibleItemCount, int totalItemCount) {
            lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {

            if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
                    && lastVisibleIndex == mResultAdapter.getCount()
                    && lvResult.getFooterViewsCount() != 0) {
                requestResultTask = new RequestSearchResultTask(
                        MoviesApplication.getInstance(), currentPage, oldWord, searchVt, null);
                requestResultTask.start();
            }
        }
    }

    private void saveToHistory(String word) {
        if (!TextUtils.isEmpty(word)) {
            historywords.getWords().remove(word);
            if (historywords.getWords().size() == MoviesConstant.SEARCH_RECORD_MAXIMUM_SIZE) {
                historywords.getWords().remove(
                        MoviesConstant.SEARCH_RECORD_MAXIMUM_SIZE - 1);
            }
            historywords.getWords().add(0, word);
            searchHistoryDao.save(word);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        MoviesApplication.getInstance().setmPgvLastPageId(BigDataConstants.PGV_CURRENT_ID_SEARCH);
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Map<String, String> pgvMap = new HashMap<String, String>();
        pgvMap.put(BigDataApi.REF, MoviesApplication.getInstance().getmPgvLastPageId());
        BigDataApi.bigDataPageShowReport(BigDataConstants.PGV_CURRENT_ID_SEARCH, pgvMap, this);
        try{
            MobclickAgent.onResume(this);
            registerCheckNetwork();
        } catch (Exception e) {
           e.printStackTrace();
        }

        BigDataSearchBean resumeBean = new BigDataSearchBean();
        resumeBean.setModule("home_page");
        BigDataApi.bigDataSearchReport(resumeBean);
    }

    private class SearchTextWatcher implements TextWatcher {

        private boolean isPause = false;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.length() > 0) {
                String str = s.toString().trim();
                if (str.length() > 0) {
                    if (!str.equals(oldWord)) {
                        oldWord = str;
                        if (!isPause) {
                            if (requestSuggestTask != null
                                    && !requestSuggestTask.isCancelled()) {
                                requestSuggestTask.cancel();
                            }
                            requestSuggestTask = new RequestSuggestWordsTask(
                                    MoviesApplication.getInstance(), str);
                            requestSuggestTask.start();
                        }
                        resume();
                    }
                }
                mDelete.setVisibility(View.VISIBLE);
            } else {
                mDelete.setVisibility(View.GONE);
                setState(SearchState.HISTORY, historywords);
            }
        }

        /**
         * 暂停一次
         */
        public void pauseOneTime() {
            isPause = true;
        }

        public void resume() {
            isPause = false;
        }
    }

    private synchronized void setState(SearchState state, SearchKeyWords words, SearchResultList result) {
        switch (state) {
            case HISTORY:
                displayHistory(words);
                break;
            case RESULT:
                displayResult(result);
                break;
            case SUGGEST:
                displaySuggest(words);
                break;
            case LOADING:
                displayLoading();
                break;
            default:
                break;
        }
    }

    private void setState(SearchState state, SearchKeyWords words) {
        if (state != SearchState.RESULT) {
            setState(state, words, null);
        }
    }

    private void setState(SearchState state, SearchResultList list) {
        if (state == SearchState.RESULT) {
            setState(state, null, list);
        }
    }


    /**
     * qinguoli
     * 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        intentfilter.addAction(Utils.SDCARD_NOSPACE_ACTION);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli
     * 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }


    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getAction().equals(PlayerUtils.CONNECTIVTY_CHANGE)) {
                    //读取保存的之前网络状态
                    SharedPreferences priorNetState = getSharedPreferences("priornetstate",
                            Activity.MODE_PRIVATE);

                    int priorNetType = priorNetState.getInt("netstate", 2);

                    int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);


                    SharedPreferences.Editor editor = priorNetState.edit();

                    editor.putInt("netstate", nowNetType);
                    editor.commit();
                }
                if (intent.getAction().equals(Utils.SDCARD_NOSPACE_ACTION)) {
                    DialogUtil.getInstance(SearchActivity.this).checkSDCardSpaceDialog();
                }


            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterCheckNetwork();
    }

    private void registerHomeKeyReceiver(Context context) {
        mHomeKeyReceiver = new HomeBackReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }

    private void unregisterHomeKeyReceiver(Context context) {
        if (null != mHomeKeyReceiver) {
            context.unregisterReceiver(mHomeKeyReceiver);
        }
    }

    public class HomeBackReceiver extends BroadcastReceiver {
        public static final String TAG = "HomeBackReceiver";
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            if ((MoviesApplication.getInstance().
                    getRunningActivityName().indexOf(SearchActivity.TAG) != -1)) {
                String action = intent.getAction();
                if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                    String reason = intent.getStringExtra(SYSTEM_REASON);
                    if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                        //表示按了home键,程序到了后台
                        LogUtils.i(SearchActivity.TAG, "post Umeng ");
                        UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_SEARCH);
                    } else if (TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)) {
                        //表示长按home键,显示最近使用的程序列表
                    }
                }
            }
        }
    }

}
